<template>
  <div>
    <div>{{denglu}}</div>
    <div>{{path}}</div>
  </div>
</template>
<script>
import Qs from 'qs'

const { config } = window; // 本项目依赖于 window.config 的配置，格式参考 deploy-cfg-example.js

export default {
  layout: 'index_default', // 加载跳转页面模板
  data() {
    return {
      ts: this.newStore(),
      denglu:"未登录",
      path: '',
      url: '',
      pm: '',

      docList: [],
      doctorInfo: {},
      
      ts: this.newStore(),
      tq: this.getData(),
    };
  },
  created() {

  },
  mounted() {
    
    const query = Qs.parse(window.location.search.substring(1))

    if (query.path != null && query.path != '') {
      this.path = query.path;
    }

    this.url = `${this.path}`.split('$$')[0];
    this.pm = `${this.path}`.split('$$')[1];

    let code = query.code;
    if (config.MODE == 'dev') {
      this.getUserInfoByDev();
    } else {
    if(code&&code != ''){  //从微信转回，进行服务器登录
       this.doLogin(code);
       return;

    }
    //判断登录
    if(!this.checkLogin()){
      this.getWxCode();
    }
    else{
      console.info("已经登录");
      //进入index.0
      if (this.url == 'cp') { // 关注医生成功的模板消息
        this.getDocInfo();
      } else {
        this.$router.push({name:'doctor-doctorlist'});
      }
      return;
    }
    }
  },
  methods: {
    //获取医生信息, 由模板消息直接进入页面时
    getDocInfo() {
      const DATA = {
        rowsperpage: '10',
        page: '1',
        keywords: '',
        docid: `${this.pm}`,
      };
      this.tq.getDoctoList(DATA, this).then((ts) => {
        console.info(JSON.stringify(ts));
        this.docList = ts.d.DATAOBJ.DATA;
        const docInfo = this.docList[0];
        this.$router.push({name:'doctor-curePatient', query: {urlType: 'mbMsg_gz', jsonParams: JSON.stringify(docInfo)}});
      })
    },

    //判断登录
    checkLogin: function(){
      console.info("checkLogin");
    
      var rybToken = localStorage.getItem("RYBTOKEN."+config.LT);

      if(rybToken == null||rybToken == ''){
        return false;
      }
      
      let userInfo;
      let hosInfo;
      const userInfoString = localStorage.getItem("userInfo");
      const hosInfoString = localStorage.getItem("hosInfo");

      if(userInfoString && userInfoString != ''){
        userInfo = JSON.parse(userInfoString);
      }
      if(hosInfoString && hosInfoString != ''){
        hosInfo = JSON.parse(hosInfoString);
      }

      return true;
    },


    //执行登录
    getWxCode: function(){
      console.info("getWxCode:"+config.hosInfo.APPID);
      const wxLoginUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+config.hosInfo.APPID+"&redirect_uri="+encodeURI(encodeURI(config.hosInfo.SERVER_URL))+"&response_type=code&scope=snsapi_base&state=htyy#wechat_redirect";
      //改成ajax试试
      window.location = wxLoginUrl;

      return;
    },

    doLogin: function(code){
      console.info("code = "+code);

      //const loginUrl = "https://zyext.renyibao.com/LoginServlet?reqType=wxmplogin&lt="+config.LT+"&sid="+config.hosInfo.SID+"&code="+code;

      const loginUrl = `https://zyext.kejizhongyi.com/LoginServlet?reqType=wxmplogin&lt=${config.LT}&sid=${config.hosInfo.SID}&code=${code}`;

      this.spost(this.ts, loginUrl).then((response) => {
        if(response.d.errCode&&response.d.errCode=='509'){  //未注册
          localStorage.setItem('openid', response.d.errMessage);  //errMessage存放openid
          this.$router.push('/signup')
          return;
        }
        if(response.d.rybToken){

          if(response.d.rybData.patsh != 'y'){
            this.$router.push('/shenhe');
            return;
          }

          localStorage.setItem("RYBTOKEN."+config.LT, response.d.rybToken);

          const userInfo = response.d.rybData;

          if(userInfo){
            localStorage.setItem("userInfo."+config.LT,JSON.stringify(userInfo));
          }

          console.info("登录成功");
          this.$router.push('/login');
        }
      });

    },
getUserInfoByDev() { /* 本地调试登录 */
      // let alert(code);
                 let res   = {
          RYBID: 'PAT'
        }
      this.spost(this.ts, `${config.APIRootDev}/doctor/LocalDevLogin.dev`,res).then((response) => {
        console.log(JSON.stringify(response));
        if (response.d.RESULT == '514' || response.d.RESULT == '515' || response.d.RESULT == '516') {
          this.$messagebox('登录失败', `${response.d.RESULTTEXT}`);
          return;
        }
        // 跳转审核页
        if (response.d.rybData.patsh != 'y') {
          this.$router.push('/shenhe')
          return;
        }
        // 跳转到注册页
        if (response.d.errCode == '513') {
          this.$router.push('/signup')
          return;
        }
        if(response.d.rybToken){
          localStorage.setItem("RYBTOKEN."+config.LT, response.d.rybToken);

          const userInfo = response.d.rybData;

          if(userInfo){
            localStorage.setItem("userInfo."+config.LT,JSON.stringify(userInfo));
          }
         
        }

         this.$router.push({name:'doctor-doctorlist'});
      }).catch((err) => {
        sessionStorage.setItem('error', JSON.stringify(err));
      });
    },
      getInitParam(){
          const hosInfo = {
            hosid :'htyy',
            hosname: '天津东丽华天医院'
          }
          
          localStorage.setItem("hosInfo",JSON.stringify(hosInfo));

    },
  },
  
};
</script>
